package com.sharkburner.aeris.dao.impl;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import com.sharkburner.aeris.bean.UserBean;
import com.sharkburner.aeris.dao.UserDao;
import com.sharkburner.aeris.dao.entity.User;
import com.sharkburner.common.dao.impl.GenericDao;

@Repository
public class UserDaoImpl extends GenericDao<User> implements UserDao {

	@Override
	public UserBean findByName(String name) {
		Criteria criteria = getCriteria();
		criteria.createAlias("group", "g");
		criteria.setProjection(Projections.projectionList()
				.add(Projections.property("fullName"), "fullName")
				.add(Projections.property("email"), "email")
				.add(Projections.property("password"), "password")
				.add(Projections.property("g.name"), "groupName"));
		criteria.add(Restrictions.like(criteria.getAlias() + ".email", name,
				MatchMode.EXACT));
		criteria.setResultTransformer(Transformers.aliasToBean(UserBean.class));
		return (UserBean) criteria.uniqueResult();
	}

	public UserBean find(String name, String password) {
		Criteria criteria = getCriteria();
		criteria.createAlias("group", "g");
		criteria.setProjection(Projections.projectionList()
				.add(Projections.property("fullName"), "fullName")
				.add(Projections.property("email"), "email")
				.add(Projections.property("password"), "password")
				.add(Projections.property("g.name"), "groupName"));
		criteria.add(Restrictions.like(criteria.getAlias() + ".email", name,
				MatchMode.EXACT));
		criteria.add(Restrictions.like(criteria.getAlias() + ".password",
				password, MatchMode.EXACT));
		criteria.setResultTransformer(Transformers.aliasToBean(UserBean.class));
		return (UserBean) criteria.uniqueResult();
	}

}
